import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { Link, history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { queryCurrentUserUsingGET } from './services/swagger/user';
import HeaderContent from '@/components/HeaderContent';
import { queryDynamicRoutersUsingGET } from './services/swagger/menu';
import { LinkOutlined } from '@ant-design/icons';
import type { MenuDataItem } from '@ant-design/pro-layout';
import defaultMenus from '../config/routes';
import type { RequestOptionsInit } from 'umi-request';
import { localRead } from './utils';
import errorHandler from './utils/errorHandler';
import { isDev, loginPath } from './utils/constants';
import fixMenuItemIcon from './utils/fixMenuItemIcon';
import defaultSettings from '../config/defaultSettings';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  collapsed?: boolean;
  menuData?: MenuDataItem[] | undefined;
  currentUser?: API.UserProfileVo;
  fetchMenuData?: () => Promise<API.RouterVo[] | undefined>;
  fetchUserInfo?: () => Promise<API.UserProfileVo | undefined>;
}> {
  // 获取动态菜单路由
  const fetchMenuData = async () => {
    try {
      const response = await queryDynamicRoutersUsingGET();
      return response.data;
    } catch (error) {
      console.log('获取动态菜单路由异常', error);
      history.push(loginPath);
    }
    return undefined;
  };

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await queryCurrentUserUsingGET();
      return response.data;
    } catch (error) {
      console.log('获取用户信息异常', error);
      history.push(loginPath);
    }
    return undefined;
  };

  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    // 从服务器加载菜单,用户信息
    // const menuData = await fetchMenuData();
    // const currentUser = await fetchUserInfo();
    let menuData
    const [menuList, currentUser] = await Promise.all([fetchMenuData(), fetchUserInfo()]);
    if (menuList) {
      menuData = [...defaultMenus, ...menuList]
    } else {
      menuData = [...defaultMenus]
    }

    return {
      fetchMenuData,
      fetchUserInfo,
      currentUser,
      menuData,
      settings: defaultSettings,
    };
  }
  return {
    fetchMenuData,
    fetchUserInfo,
    menuData: defaultMenus,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const onCollapse = (collapsed: boolean) => {
    setInitialState({
      ...initialState,
      collapsed,
    }).then();
  }
  // 处理菜单数据
  const menuDataRender = () => {
    const menuList = initialState?.menuData || []
    return fixMenuItemIcon(menuList);
  };

  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // 系统水印
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    // 去除系统自带 collapsedButton
    collapsedButtonRender: false,
    // 指定配置collapsed
    collapsed: initialState?.collapsed,
    // 菜单折叠事件
    onCollapse: onCollapse,
    // 自定义头内容方法
    headerContentRender: () => (
      <HeaderContent collapse={initialState?.collapsed} onCollapse={onCollapse} />
    ),
    footerRender: () => <Footer />,
    // 从服务器动态获取菜单
    menuDataRender: () => menuDataRender(),
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
        <Link to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>,
        // <Link to="/~docs">
        //   <BookOutlined />
        //   <span>业务组件文档</span>
        // </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

// request 请求拦截器
const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  const tokenInfo = localRead('UserToken');
  if (tokenInfo) {
    const { tokenHead, token } = tokenInfo;
    const authHeader = { Authorization: tokenHead + token };
    return {
      url: `${url}`,
      options: { ...options, interceptors: true, headers: authHeader },
    };
  }
  return {
    url: `${url}`,
    options: { ...options, interceptors: true },
  };
};

const baseUrl = isDev ? '' : '';

/**
 * 网络请求配置
 * @see https://beta-pro.ant.design/docs/request-cn
 */
export const request: RequestConfig = {
  // 超时时间
  timeout: 5000,
  prefix: `${baseUrl}`,
  errorHandler,
  errorConfig: {
    adaptor: (res) => {
      return {
        success: res.code === 20000,
        errorCode: res.code,
        errorMessage: res.message,
      };
    },
  },
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
  // responseInterceptors: [appResponseInterceptors],
};
